package com.example.mall.dao;

import com.example.mall.model.PersonInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class PersonInfoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(PersonInfo personInfo) {
        String sql = "insert into personInfo (name, idR, sex) values (?, ?, ?)";
        jdbcTemplate.update(sql, personInfo.getId(), personInfo.getName(), personInfo.getIdR(), personInfo.getAvatl(), personInfo.getSex());
    }

    public void delete(Integer id) {
        String sql = "delete from personInfo where id = ?";
        jdbcTemplate.update(sql, id);
    }

    public int updateAvatlById(PersonInfo personInfo) {
        String sql = "update personInfo set avatl = ? where id = ?";
        return jdbcTemplate.update(sql, personInfo.getAvatl(), personInfo.getId());
    }

    public int updateSexById(PersonInfo personInfo) {
        String sql = "update personInfo set sex = ? where id = ?";
        return jdbcTemplate.update(sql, personInfo.getSex(), personInfo.getId());
    }

    public PersonInfo getById(Integer id) {
        String sql = "select * from personInfo where id = ? lock in share mode";
        RowMapper<PersonInfo> rowMapper = new BeanPropertyRowMapper<>(PersonInfo.class);
        PersonInfo personInfo = null;
        try {
            personInfo = jdbcTemplate.queryForObject(sql, rowMapper, id);
        }
        catch (Exception e) {
            return personInfo;
        }
        return personInfo;
    }

    public PersonInfo getByIdR(String idR) {
        String sql = "select * from personInfo where idR = ? lock in share mode";
        RowMapper<PersonInfo> rowMapper = new BeanPropertyRowMapper<>(PersonInfo.class);
        PersonInfo personInfo = null;
        try {
            personInfo = jdbcTemplate.queryForObject(sql, rowMapper, idR);
        }
        catch (Exception e) {
            return personInfo;
        }
        return personInfo;
    }

}
